import { useEffect, useState } from 'react'
import ChatBox from './components/ChatBox'
import DirBar from './components/DirBar'
import Parse from 'parse'
import './App.scss'
import 'antd/dist/antd.css'
import LoginPage from './components/LoginPage'
import SignPage from './components/SignPage'

Parse.initialize('layouwen')
Parse.serverURL = 'https://de3.e-path.cn/parse'

function App () {
  const [isLogin, setIsLogin] = useState(false)
  const [pageStatus, setPageStatus] = useState(1)
  const [chatGroup, setChatGroup] = useState([])
  const [curChat, setCurChat] = useState(null)

  useEffect(() => {
    const userinfo = localStorage.getItem('Parse/layouwen/currentUser')
    if (userinfo) {
      setIsLogin(true)
      void getChatGroup()
    }
  }, [])

  useEffect(() => {
    if (isLogin) void getChatGroup()
  }, [isLogin])

  const getChatGroup = async () => {
    try {
      const roles = await new Parse.Query(Parse.Role).find()
      const groups = []
      for (let i = 0; i < roles.length; i++) {
        const users = await roles[i].attributes.users.query().find()
        const flag = users.some(item => Parse.User.current().id === item.id)
        if (flag) groups.push(roles[i].attributes.name)
      }
      if (groups.length > 0) setCurChat(groups[0])
      setChatGroup(groups)
    } catch (err) {
      console.error(err)
    }
  }

  const toggleChatBox = (chatName) => {
    setCurChat(chatName)
  }

  const logOut = () => {
    setIsLogin(false)
    localStorage.clear()
  }

  return (
    <div className="App">
      {isLogin ? <>
        <DirBar list={chatGroup} logOut={logOut} toggle={toggleChatBox} />
        <ChatBox curChat={curChat} />
      </> : pageStatus === 1 ? <LoginPage login={setIsLogin} setPage={setPageStatus} /> :
        <SignPage login={setIsLogin} setPage={setPageStatus} />
      }
    </div>
  )
}

export default App
